package com.finger.forest;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.dialog.PopupWindowForUploadHead;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.GridUserModel;
import com.finger.forest.model.InsertUserInfoModel;
import com.finger.forest.model.UserManagerModel;
import com.finger.forest.utils.AndroidUtil;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.ToastUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 新增用户
 */
public class AddNewUserActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    @BindView(R.id.ivLeft)
    ImageView ivLeft;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.rivHead)
    RoundedImageView rivHead;

    @BindView(R.id.etUserName)
    EditText etUserName;
    @BindView(R.id.etRealName)
    EditText etRealName;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etPass)
    EditText etPass;

    @BindView(R.id.tvJurisdiction)
    TextView tvJurisdiction;
    @BindView(R.id.tvOnDuty)
    TextView tvOnDuty;

    @BindView(R.id.bnSave)
    Button bnSave;
    @BindView(R.id.clContent)
    ConstraintLayout clContent;

    private List<String> mJurisdictionItems = new ArrayList<>();
    private List<String> mOnDutyItems = new ArrayList<>();

    private PopupWindowForUploadHead popupWindowForUploadHead;

    private GridUserModel userManagerModel;

    @Override
    protected int setView() {
        return R.layout.activity_add_new_user;
    }

    @Override
    protected void receiveData() {
        userManagerModel = (GridUserModel) getIntent().getSerializableExtra("userManagerModel");
    }

    @Override
    protected void initializeView() {
        tvTitle.setText("新增用户");

        if (null == userManagerModel) {
            mJurisdictionItems.add("管理员");
            mJurisdictionItems.add("普通用户");

            mOnDutyItems.add("无人");
            mOnDutyItems.add("有人");

            clicks();

            bnSave.setVisibility(View.VISIBLE);
        } else {

            Glide.with(context)
                    .load(userManagerModel.getHeadPortraitRul())
                    .placeholder(R.mipmap.header)
                    .dontAnimate()
                    .into(rivHead);

            etUserName.setText(StringUtil.isNull(userManagerModel.getName()));
            etUserName.setFocusable(false);
            etRealName.setText(StringUtil.isNull(userManagerModel.getName()));
            etRealName.setFocusable(false);
            etPhone.setText(StringUtil.isNull(userManagerModel.getCellphone()));
            etPhone.setFocusable(false);
            etPass.setText(StringUtil.isNull(userManagerModel.getPassword()));
            etPass.setFocusable(false);

            /*tvJurisdiction.setText(userManagerModel.getRoleType() == 1 ? "管理员" : "普通用户");
            tvOnDuty.setText(userManagerModel.getDuty() == 1 ? "有人" : "无人");*/

            bnSave.setVisibility(View.GONE);

        }
        //返回
        RxView.clicks(ivLeft).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });
    }

    private void clicks() {
        //上传头像
        RxView.clicks(rivHead).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            if (null == popupWindowForUploadHead) {
                popupWindowForUploadHead = new PopupWindowForUploadHead(AddNewUserActivity.this, clickListener);
            }
            popupWindowForUploadHead.showAtLocation(clContent,
                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        });

        //保存
        RxView.clicks(bnSave).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            String loginUserName = etUserName.getText().toString().trim();
            if (StringUtil.isBlank(loginUserName)) {
                ToastUtils.show("请输入登录账号");
                return;
            }

            String userName = etRealName.getText().toString().trim();
            if (StringUtil.isBlank(userName)) {
                ToastUtils.show("请输入真实姓名");
                return;
            }

            String jurisdiction = tvJurisdiction.getText().toString().trim();
            /*if (StringUtil.isBlank(jurisdiction)) {
                ToastUtils.show("请选择角色权限");
                return;
            }*/

            String onDuty = tvOnDuty.getText().toString().trim();
            /*if (StringUtil.isBlank(onDuty)) {
                ToastUtils.show("请选择值守情况");
                return;
            }*/

            String phone = etPhone.getText().toString().trim();
            if (StringUtil.isBlank(phone)) {
                ToastUtils.show("请输入移动号码");
                return;
            }

            String pass = etPass.getText().toString().trim();
            if (StringUtil.isBlank(pass)) {
                ToastUtils.show("请输入初始密码");
                return;
            }

            /*if (null == uploadFile) {
                ToastUtils.show("请上传头像");
                return;
            }*/


            Map<String, RequestBody> maps = new HashMap<>();
            maps.put("userName", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), loginUserName));
            maps.put("password", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), pass));
            maps.put("cellphone", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), phone));
            maps.put("name", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), loginUserName));
            maps.put("roleType", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), jurisdictionType(jurisdiction)));
            maps.put("duty", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), dutyType(onDuty)));

            MultipartBody.Part requestImgPart = null;
            if (uploadFile != null) {
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), uploadFile);
                requestImgPart =
                        MultipartBody.Part.createFormData("headPortFile", uploadFile.getPath(), requestFile);
            }

            showPd();
            presenter.insertUserInfo(maps, requestImgPart);
        });

        //权限
        RxView.clicks(tvJurisdiction).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etUserName);
            loadJurisdiction();
        });

        //值守情况
        RxView.clicks(tvOnDuty).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etUserName);
            loadOnDuty();
        });
    }

    private String dutyType(String onDuty) {
        String type = "";
        if (onDuty.equals("无人")) {
            type = "0";
        }

        if (onDuty.equals("有人")) {
            type = "1";
        }
        return type;
    }

    private String jurisdictionType(String jurisdiction) {
        String type = "";
        if (jurisdiction.equals("管理员")) {
            type = "1";
        }

        if (jurisdiction.equals("普通用户")) {
            type = "2";
        }
        return type;
    }

    @Override
    protected void loadDataFromServer() {

    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //拍照
                case R.id.cameraBn:
                    //选择拍照，需要先给照相机权限
                    requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x002);
                    break;

                case R.id.selectBn:
                    //选择照片，需要先给存储权限
                    requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x003);
                    break;


                default:
                    break;
            }
        }
    };

    @Override
    public void permissionSuccess(int requestCode) {
        if (requestCode == 0x002) {
            openCamera(activity);
            popupWindowForUploadHead.dismiss();
        }

        if (requestCode == 0x003) {
            selectPhoto();
            popupWindowForUploadHead.dismiss();
        }
    }

    /**
     * 选择照片
     */
    private void selectPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 判断系统中是否有处理该 Intent 的 Activity
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_IMAGE_GET);
        } else {
            ToastUtils.show("未找到图片查看器");
        }
    }

    /**
     * 打开相机拍照
     *
     * @param activity
     */
    public File tempFile;
    private static final int PHOTO_REQUEST_CAREMA = 2;
    private static final int CROP_IMAGE2 = 4;
    private static final int REQUEST_IMAGE_GET = 0;
    private Uri outputFileUri;  //拍照获得的图片的uri

    public void openCamera(Activity activity) {
        //获取系统版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    filename + ".jpg");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                outputFileUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                outputFileUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        activity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
     * 判断sdcard是否被挂载
     */
    public boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        //拍照
        if (requestCode == PHOTO_REQUEST_CAREMA) {
            if (outputFileUri != null) {
                startPhotoZoom(outputFileUri);  //裁剪
            }
        }

        //选择照片
        if (requestCode == REQUEST_IMAGE_GET) {
            getPicture(data);
        }

        //裁剪
        if (requestCode == CROP_IMAGE2) {
            if (data != null) {
                setPicToView(data);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getPicture(Intent data) {
        // 从相册中获取照片
        if (data == null) {
            return;
        } else {
            // 获取相册图片的uri
            Uri galleryUri = data.getData();
            try {
                // 裁剪图片
                startPhotoZoom(galleryUri);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_IMAGE2);  //返回去
    }

    private File photoFile;
    private File uploadFile;

    //裁剪之后的图片不能放回原地址，所以要存放在一个临时file中再上传
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            rivHead.setImageBitmap(photo);

            photoFile = getFile(photo);

            luBan(photoFile);

        }
    }

    private void luBan(File imgFile) {
        Luban.with(this)
                .load(imgFile)
                .ignoreBy(100)
                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        Log.e("onStart", "onStart");
                    }

                    @Override
                    public void onSuccess(File file) {
                        uploadFile = file;
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        Log.e("Throwable", e.getMessage());
                    }
                }).launch();
    }


    //在这里抽取了一个方法   可以封装到自己的工具类中...
    public File getFile(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        File filePath = null;
        try {
            filePath = new File("data/data/com.finger.forest/" + System.currentTimeMillis() + ".png");
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePath);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            int x = 0;
            byte[] b = new byte[1024 * 100];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    private OptionsPickerView pvJurisdictionOptions;

    private int mJurisdictionPosition;

    private void loadJurisdiction() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvJurisdictionOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mJurisdictionItems.get(options1);
                mJurisdictionPosition = options1;
                tvJurisdiction.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择角色权限");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvJurisdictionOptions.returnData();
                                pvJurisdictionOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvJurisdictionOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvJurisdictionOptions.setPicker(mJurisdictionItems);//添加数据
        pvJurisdictionOptions.show();
    }


    private OptionsPickerView pvOnDutyOptions;

    private int mOnDutyPosition;

    private void loadOnDuty() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvOnDutyOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mOnDutyItems.get(options1);
                mOnDutyPosition = options1;
                tvOnDuty.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择值守情况");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOnDutyOptions.returnData();
                                pvOnDutyOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOnDutyOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvOnDutyOptions.setPicker(mOnDutyItems);//添加数据
        pvOnDutyOptions.show();
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag
                    .INSERT_USER_INFO:
                InsertUserInfoModel insertUserInfoModel = (InsertUserInfoModel) model;
                if (null != insertUserInfoModel) {
                    ToastUtils.show(msg);
                    setResult(RESULT_OK);
                    finish();
                }
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        ToastUtils.show(message);
    }
}